//
//  BookRideViewController.m
//  Yogofly
//
//  Created by Meracom on 6/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "BookRideViewController.h"
#import "MapDirectionsViewController.h"
#import "BookRideInfoViewController.h"
#import "UINavigationBar+CustomImage.h"
#import "Utility.h"
#import "AppDelegate.h"

@implementation BookRideViewController

@synthesize startField;
@synthesize endField;
@synthesize datePicker;
@synthesize dateField;
@synthesize tbarKeyboard;

#define kFieldTag_Start     1
#define kFieldTag_End     2
#define kFieldTag_Date  3
#define kFieldTag_Passengers  4
#define kFieldTag_Notes  5
#define kTableViewTag_StartPoint    1
#define kTableViewTag_EndPoint    2

#define PlacesURL @"https://maps.googleapis.com/maps/api/place/autocomplete/xml?input=\"%@\"&types=geocode&language=fr&sensor=true&key=AIzaSyC1WP96t3UMLVDptXDSa8NxYd2SyVfNKOA"

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Step 1";
    [[Utility Shared] loadNavigationIOS5];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    placesOutputArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    for (UITextField *txt in self.view.subviews) {
        if ([txt isKindOfClass:[UITextField class]]) {
            txt.inputAccessoryView = self.tbarKeyboard;
        }
    }
    
    datePicker.datePickerMode = UIDatePickerModeDate;
    dateField.inputView = datePicker;
    
    [self createLeftBarButton];
    [self createTableViewStartPoint];
    [self createTableViewEndPoint];
    
    // Do any additional setup after loading the view from its nib.
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - CREATE UI

- (void)createLeftBarButton{
    UIImage *imgBack = [UIImage imageNamed:@"iconLeft.png"];
    UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnBack setBackgroundImage:imgBack forState:UIControlStateNormal];
    [btnBack addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btnLeft = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem= btnLeft;
    btnLeft.customView.frame = CGRectMake(0.0f, 0.0f, imgBack.size.width-24, imgBack.size.height-15);
    [btnLeft release];
}

- (void)createTableViewStartPoint{
    tblStartPoint = [[UITableView alloc] initWithFrame:CGRectMake(30, 73, 255, 238) style:UITableViewStylePlain];
    tblStartPoint.delegate = self;
    tblStartPoint.dataSource = self;
    tblStartPoint.scrollEnabled = YES;
    tblStartPoint.tag = kTableViewTag_StartPoint;
    tblStartPoint.hidden = YES;  
    [self.view addSubview:tblStartPoint];
}

- (void)createTableViewEndPoint{
    tblEndPoint = [[UITableView alloc] initWithFrame:CGRectMake(30, 132, 255, 238) style:UITableViewStylePlain];
    tblEndPoint.delegate = self;
    tblEndPoint.dataSource = self;
    tblEndPoint.scrollEnabled = YES;
    tblEndPoint.tag = kTableViewTag_EndPoint;
    tblEndPoint.hidden = YES;  
    [self.view addSubview:tblEndPoint];
}

#pragma mark - ACTION

- (void)onBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)showMapViewController:(id)sender{
    if ([endField.text isEqualToString:@""]  || [startField.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"WARNING" message:@"Please enter pickup or destination " delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    else {
        MapDirectionsViewController *controller = [[MapDirectionsViewController alloc] init];
        
        //controller.startPoint = startField.text;
        //controller.endPoint = endField.text;
        
        controller.startPoint = endField.text;
        controller.endPoint = startField.text;
        
        NSMutableArray *wayPoints = [NSMutableArray arrayWithCapacity:0];
        controller.wayPoints = wayPoints;
        controller.travelMode = UICGTravelModeDriving;
        
        [self.navigationController pushViewController:controller animated:YES];
        [controller release];
    }
}

- (IBAction)showDetailBookRide:(id)sender{
    BookRideInfoViewController *vcBookRideInfo = [[BookRideInfoViewController alloc] initWithNibName:@"BookRideInfoViewController" bundle:nil];
    vcBookRideInfo.strDrop = [NSString stringWithFormat:@"%@",endField.text];
    vcBookRideInfo.strPickUp = [NSString stringWithFormat:@"%@",startField.text];
    vcBookRideInfo.strDate = [NSString stringWithFormat:@"%@",dateField.text];
    NSString * strCity = startField.text;
    NSArray *arrayCity = [strCity componentsSeparatedByString:@","];
    //NSLog(@"%@",[arrayCity objectAtIndex:0]);
    vcBookRideInfo.strCityName = [NSString stringWithFormat:@"%@",[arrayCity objectAtIndex:0]];
    [self.navigationController pushViewController:vcBookRideInfo animated:YES];
    [vcBookRideInfo release];
}
- (IBAction)onCloseKeyboard:(id)sender{
    NSDateFormatter* dateFormatter1 = [[NSDateFormatter alloc] init];
    [dateFormatter1 setDateStyle:NSDateFormatterNoStyle];
    [dateFormatter1 setDateFormat:@"dd/MM/yyyy"];
    
    NSString* strDateSelect = [dateFormatter1 stringFromDate:[datePicker date]];
    [dateFormatter1 release];
    
    for (UITextField *txt in self.view.subviews) {
        if ([txt isKindOfClass:[UITextField class]]) {
            [txt resignFirstResponder];
            if ([txt.inputView isKindOfClass:[UIDatePicker class]]) {
                dateField.text = [NSString stringWithFormat:@"%@", strDateSelect];
            }
        }
    }
    if (self.view.frame.origin.y != 0) {
        [self moveViewAnimation:0];
    }
    if (tblStartPoint.hidden == NO) 
            tblStartPoint.hidden = YES;
    if (tblEndPoint.hidden == NO)
        tblEndPoint.hidden = YES;
    

}
- (void)moveViewAnimation : (NSInteger)pam {
    [UIView beginAnimations: @"moveField_Date" context: nil];
    [UIView setAnimationDelegate: self];
    [UIView setAnimationDuration: 0.25f];
    [UIView setAnimationCurve: UIViewAnimationCurveEaseInOut];

    self.view.frame = CGRectMake(0, pam, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}

- (void)closeInputView{
    for (UITextField *txt in self.view.subviews) {
        if ([txt isKindOfClass:[UITextField class]]) {
            [txt resignFirstResponder];
        }
    }
    if (self.view.frame.origin.y != 0) {
        [self moveViewAnimation:0];
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField.tag == kFieldTag_Date) {
        [self moveViewAnimation:-100];
    }
    if (textField.tag == kFieldTag_Notes) {
        [self moveViewAnimation:-220];
    }
    if (textField.tag == kFieldTag_Passengers) {
        [self moveViewAnimation:-160];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSLog(@"%@",textField.text);
    NSLog(@"%@",string);
    
    [placesOutputArray removeAllObjects];
    NSString * str = [NSString stringWithFormat:@"%@%@",textField.text, string];
    NSString *strURL = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/autocomplete/xml?input=%@&types=geocode&language=fr&sensor=true&key=AIzaSyC1WP96t3UMLVDptXDSa8NxYd2SyVfNKOA", str];
    
    
    NSURL *googlePlacesURL = [NSURL URLWithString:strURL];
    NSData *xmlData = [NSData dataWithContentsOfURL:googlePlacesURL];
    xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:nil];
    
    NSArray *arr = [xmlDocument.rootElement elementsForName:@"prediction"];
    
    for(GDataXMLElement *e in arr )
    {
        [placesOutputArray addObject:e];
    }
    
    if (textField.tag == kFieldTag_Start) {
        tblStartPoint.hidden = NO;
        [tblStartPoint reloadData];
    }
    else if (textField.tag == kFieldTag_End){
        [self moveViewAnimation:-50];
        tblEndPoint.hidden = NO;
        [tblEndPoint reloadData];
    }

    /*
    NSString *substring = [NSString stringWithString:textField.text];
    substring = [substring stringByReplacingCharactersInRange:range withString:string];
    [self searchAutocompleteEntriesWithSubstring:substring];
     */
    return YES;
}

#pragma mark UITableViewDataSource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
    return [placesOutputArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    static NSString *AutoCompleteRowIdentifier = @"AutoCompleteRowIdentifier";
    cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] 
                 initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    //cell.textLabel.text = [autocompleteUrls objectAtIndex:indexPath.row];
    //cell.textLabel.text = @"VINH";
    cell.textLabel.text = [[[placesOutputArray objectAtIndex:indexPath.row] childAtIndex:0] stringValue];
    cell.textLabel.font = [UIFont systemFontOfSize:13];
    //cell.textLabel.font = [UIFont systemFontSize];
    return cell;
}

#pragma mark UITableViewDelegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //urlField.text = selectedCell.textLabel.text;
    
    //[self goPressed];
    UITableViewCell *selectedCell;
    if (tableView.tag == kTableViewTag_StartPoint) {
        selectedCell = [tableView cellForRowAtIndexPath:indexPath];
        startField.text = [NSString stringWithFormat:@"%@",selectedCell.textLabel.text];
        [self closeInputView];
        tblStartPoint.hidden = YES;
    }
    else if (tableView.tag == kTableViewTag_EndPoint){
        selectedCell = [tableView cellForRowAtIndexPath:indexPath];
        endField.text = [NSString stringWithFormat:@"%@",selectedCell.textLabel.text];
        [self closeInputView];
        tblEndPoint.hidden = YES;
    }
}

@end
